﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
using System.Globalization;

public partial class ajax_updatework : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["id_user"] != null && Session["permission"] != null
            && (((int)Session["permission"]) >= 2))
        {
            //'content':content_work,
            //'des':$('#des_work').val(),
            //'catalogId':$('#catalog_work').val(),
            //'priority':$('#priority_work').val(),
            //'userId':$('#username_work').val(),
            //'start':$('#start_work').val(),
            //'end':$('#end_work').val()
            try
            {
                string type = "Update"; // check update or add a new work
                int leaderId = Int32.Parse(Session["id_user"].ToString());
                int catalogId = Int32.Parse(Request["catalogId"]);
                string sql = "SELECT projectId FROM [catalog] WHERE id=" + comm.to_sql(catalogId.ToString(), "number");
                DataTable dtTable = dal.SelectTable(sql);
                int projectId = 0;
                if (dtTable.Rows.Count == 1)
                {
                    projectId = Int32.Parse(dtTable.Rows[0]["projectId"].ToString());
                }
                else
                    throw new Exception("FAIL");

                #region check leader is enable to access this project
                SqlParameter[] listParams = new SqlParameter[3];
                //-- param 1: @userId
                SqlParameter param = new SqlParameter("@userId", leaderId);
                param.SqlDbType = SqlDbType.Int;
                param.Direction = ParameterDirection.Input;
                listParams[0] = param;

                //-- param 2: @projectId
                param = new SqlParameter("@projectId", projectId);
                param.SqlDbType = SqlDbType.Int;
                param.Direction = ParameterDirection.Input;
                listParams[1] = param;

                //-- param 3: @isAccess
                param = new SqlParameter();
                param.ParameterName = "@isAccess";
                param.SqlDbType = SqlDbType.Int;
                param.Direction = ParameterDirection.Output;
                listParams[2] = param;

                dal.ExecuteSP("proCheckAccessProject_GET", listParams);
                int enable = Int32.Parse(listParams[2].Value.ToString());
                if (enable == 0)
                    throw new Exception("FAIL");
                #endregion

                #region check leader is enable to add work to project
                if (((int)Session["permission"]) >= 4)
                {
                    sql = " SELECT permission FROM UserProject " +
                          " WHERE userId=" + comm.to_sql(leaderId.ToString(), "number") +
                          " AND projectId=" + comm.to_sql(projectId.ToString(), "number");
                    dtTable = dal.SelectTable(sql);
                    if (dtTable.Rows.Count == 1)
                    {
                        int permission = Int32.Parse(dtTable.Rows[0]["permission"].ToString());
                        if (permission >= 5)
                            throw new Exception("FAIL");
                    }
                    else
                        throw new Exception("FAIL");
                }
                #endregion

                #region get param from request
                int workId = Int32.Parse(Request["id"]);
                string content = comm.StandardString(Request["content"]);
                string des = comm.StandardString(Request["des"]);
                int priority = Int32.Parse(Request["priority"]);
                int userId = Int32.Parse(Request["username"]);
                string start = comm.RemoveSpace(Request["start"]);
                string end = comm.RemoveSpace(Request["end"]);
                #endregion

                #region check param from request
                // check content
                if (content.Length == 0)
                    throw new Exception("FAIL");
                sql = " SELECT id FROM work " +
                      " WHERE catId=" + comm.to_sql(catalogId.ToString(), "number") +
                      " AND LOWER([content])=LOWER(" + comm.to_sql(content, "string")+')';
                dtTable=dal.SelectTable(sql);
                //if (dtTable.Rows.Count >1)
                //    throw new Exception("DUPLICATE");
                //else if (dtTable.Rows.Count == 1)
                //{
                //    int id = Int32.Parse(dtTable.Rows[0]["id"].ToString());
                //    if (id != workId)
                //        throw new Exception("DUPLICATE");
                //}
                //else // check catId of workId equals to new catId => update or add a new work
                //{
                    sql = "SELECT catId FROM work WHERE id=" + comm.to_sql(workId.ToString(), "number");
                    dtTable = dal.SelectTable(sql);
                    if (dtTable.Rows.Count == 1)
                    {
                        int id = Int32.Parse(dtTable.Rows[0]["catId"].ToString());
                        if (id != catalogId)
                            type = "Add";
                    }
                    else
                        throw new Exception("FAIL");
                //}

                // check priority
                if (priority <= 0)
                    priority = 1;
                if (priority >= 5)
                    priority = 1;

                // check userId: this user joins in this project
                sql = " SELECT permission FROM UserProject " +
                      " WHERE userId=" + comm.to_sql(userId.ToString(), "number") +
                      " AND projectId=" + comm.to_sql(projectId.ToString(), "number");
                if (dal.SelectTable(sql).Rows.Count != 1)
                    throw new Exception("FAIL");

                // check start
                DateTimeFormatInfo dtfi = new DateTimeFormatInfo();
                dtfi.ShortDatePattern = "dd/MM/yyyy";
                dtfi.DateSeparator = "/";
                if (start.Length > 0)
                {
                    DateTime dateStart = Convert.ToDateTime(start, dtfi);
                    start = dateStart.Day.ToString() + "/" + dateStart.Month + "/" + dateStart.Year;
                }
                // check end
                if (end.Length > 0)
                {
                    DateTime dateEnd = Convert.ToDateTime(end, dtfi);
                    end = dateEnd.Day.ToString() + "/" + dateEnd.Month + "/" + dateEnd.Year;
                }
                #endregion

                #region update or add new a work
                if (type.ToLower() == "add")
                {
                    sql = " INSERT INTO work(catId,leaderId,userId,[content],description,start,[end],status,priority,projectId) " +
                      " VALUES(" + comm.to_sql(catalogId.ToString(), "number") + "," + comm.to_sql(leaderId.ToString(), "number") +
                      "," + comm.to_sql(userId.ToString(), "number") + "," + comm.to_sql(content, "string") +
                      "," + comm.to_sql(des, "string") + "," + comm.to_sql(start, "date") + "," + comm.to_sql(end, "date") +
                      ",1," + comm.to_sql(priority.ToString(), "number") + "," + comm.to_sql(projectId.ToString(), "number") +
                      " )";
                }
                else if (type.ToLower() == "update")
                {
                    sql = " UPDATE work " +
                      " SET catId=" + comm.to_sql(catalogId.ToString(), "number") + ",leaderId=" + comm.to_sql(leaderId.ToString(), "number") +
                      ",userId=" + comm.to_sql(userId.ToString(), "number") + ",[content]=" + comm.to_sql(content, "string") +
                      ",description=" + comm.to_sql(des, "string") + ",start=" + comm.to_sql(start, "date") + ",[end]=" + comm.to_sql(end, "date") +
                      ",status=1,priority=" + comm.to_sql(priority.ToString(), "number") +
                      " WHERE id=" + comm.to_sql(workId.ToString(), "number");
                    
                }
                if (dal.Execute(sql) == 1)
                {
                    throw new Exception("OK");
                }
                else throw new Exception("FAIL");
                #endregion
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
            }
        }
    }
}
